package com.hunttown.mes.manage.service;

import com.hunttown.mes.common.keys.KeyConstants;
import com.hunttown.mes.common.cache.Cache;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.*;
import com.hunttown.mes.rpc.api.TransportNewsRpcService;
import com.hunttown.mes.rpc.domain.TransportTableChineseEnglishDTO;
import com.hunttown.mes.rpc.domain.TransportTableChineseEnglishDetailDTO;
import com.hunttown.mes.rpc.domain.TransportNewsDTO;
import com.hunttown.mes.rpc.domain.query.TransportNewsDTOQuery;
import com.hunttown.mes.rpc.domain.query.TransportTableChineseEnglishDetailDTOQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;

import java.util.*;

/**
 * created by wangjunfu on 2020-05-26 01:40:41
 */
@Service
public class TransportNewsManageService {

    private final static Logger logger = LoggerFactory.getLogger(TransportNewsManageService.class);

    private final TransportNewsRpcService rpcService;
    private final TransportTableChineseEnglishManageService englishService;
    private final TransportTableChineseEnglishDetailManageService englishDetailService;
    private final AnalysisManageManageService manageService;
    private final Cache jedisCache;

    @Autowired
    public TransportNewsManageService(TransportNewsRpcService rpcService, TransportTableChineseEnglishManageService englishService, TransportTableChineseEnglishDetailManageService englishDetailService, AnalysisManageManageService manageService, Cache jedisCache) {
        this.rpcService = rpcService;
        this.englishService = englishService;
        this.englishDetailService = englishDetailService;
        this.manageService = manageService;
        this.jedisCache = jedisCache;
    }

    // 新增
    public TransportNewsDTO insert(TransportNewsDTO objDTO) {
        return rpcService.insert(objDTO);
    }

    // 通过ID修改
    public Boolean updateInfoById(TransportNewsDTO objDTO) {
        Boolean isNext = rpcService.updateInfoById(objDTO);
        if (isNext) {
            // 刷新缓存
            refreshCacheById(objDTO.getId());
        }
        return isNext;
    }

    // 通过Query修改
    public Boolean updateInfoByQuery(TransportNewsDTOQuery objDTOQuery) {
        Boolean isNext = rpcService.updateInfoByQuery(objDTOQuery);

        //单体刷新
        if (isNext && objDTOQuery.getW_id() != null) {
            refreshCacheById(objDTOQuery.getW_id());
        }

        //批量刷新缓存
        if (isNext && objDTOQuery.getIds() != null) {
            List<Integer> list = new ArrayList<>();
            try {
                list = (List<Integer>) objDTOQuery.getIds();
            } catch (Exception e) {
                e.printStackTrace();
            }
            refreshCacheByIdList(list);
        }
        return isNext;
    }

    // 通过ID删除
    public Boolean delete(Integer id) {
        Boolean isNext = rpcService.deleteById(id);
        if (isNext) {
            // 刷新缓存
            refreshCacheById(id);
        }
        return isNext;
    }

    // 批量删除
    public Boolean deleteForBatch(String clearIds) {

        //处理 “,5,6,7,” 为List
        List<Integer> idList = FormatUtils.commaToList_Integer(clearIds);

        if (idList.size() == 0) {
            return false;
        }

        TransportNewsDTOQuery query = new TransportNewsDTOQuery();
        query.setDeleteFlag(1);
        query.setIds(idList);

        Boolean isNext = rpcService.updateInfoByQuery(query);
        if (isNext) {
            // 刷新缓存
            refreshCacheByIdList(idList);
        }

        return isNext;
    }

    // 通过ID获取
    public TransportNewsDTO getById(Integer id) {
        if (id <= 0) {
            return null;
        }
        return rpcService.selectById(id);
    }

    // 通过短标题（英文）获取数据
    public TransportNewsDTO getByShortTitle(String shortTitle, Integer entId) {
        if (StringUtils.isBlank(shortTitle)) {
            return null;
        }

        TransportNewsDTOQuery query = new TransportNewsDTOQuery();
        if (entId != null && entId > 0) {
            query.setEntId(entId);
        }
        query.setShortTitle(shortTitle.trim());
        query.setStopFlag(0);
        return rpcService.selectObjByQuery(query);
    }

    // 通过类目ID获取（单面内容只有一个）
    public TransportNewsDTO getByCatalogId(Integer catalogId) {
        if (catalogId == null || catalogId <= 0) {
            return null;
        }

        TransportNewsDTOQuery query = new TransportNewsDTOQuery();
        query.setCatalogId(catalogId);
        query.setStopFlag(0);
        return rpcService.selectObjByQuery(query);
    }

    // 获取总文章数
    public Long getTotalCount(TransportNewsDTOQuery objDTOQuery) {
        return rpcService.getTotalCount(objDTOQuery);
    }

    /**
     * 先从缓存中获取数据
     * 如果缓存为空，从数据库中获取，并将获取的数据添加到缓存。
     *
     * @param id id
     * @return obj
     */
    public TransportNewsDTO getFromCacheId(Integer id) {
        if (id == null || id <= 0) {
            return null;
        }

        TransportNewsDTO obj = jedisCache.oget(KeyConstants.NEWS_INFO_KEY_ID + id, TransportNewsDTO.class);
        if (obj == null) {
            obj = getById(id);
            if (obj != null) {
                jedisCache.oset(KeyConstants.NEWS_INFO_KEY_ID + id, obj);
            }
        }

        return obj;
    }

    // 通过Query获取
    public TransportNewsDTO getByQuery(TransportNewsDTOQuery objDTOQuery) {
        return rpcService.selectObjByQuery(objDTOQuery);
    }

    // 获取分页列表
    public Page<TransportNewsDTO> getForPage(TransportNewsDTOQuery objDTOQuery) {
        return rpcService.getListForPage(objDTOQuery);
    }

    // 改变某条记录的使用状态
    public Boolean changeState(Integer id, Integer state) {
        TransportNewsDTO obj = new TransportNewsDTO();
        obj.setStopFlag(state);
        obj.setId(id);
        return updateInfoById(obj);
    }

    /**
     * 刷新文章缓存
     *
     * @param id 文章id
     */
    public void refreshCacheById(Integer id) {
        if (id == null || id <= 0) {
            return;
        }

        TransportNewsDTO obj = getById(id);
        if (obj != null) {
            jedisCache.delete(KeyConstants.NEWS_INFO_KEY_ID + id);
        }
    }

    /**
     * 刷新文章缓存(批量)
     *
     * @param idList ids
     */
    public void refreshCacheByIdList(List<Integer> idList) {
        if (idList == null || idList.size() == 0) {
            return;
        }

        for (Integer id : idList) {
            refreshCacheById(id);
        }
    }

    //region 数据查看

    /**
     * 组装实体信息为前台可展示的格式
     * 可做定制化的配置
     * 存放位置：各业务的Service中
     *
     * @param model     Sevelet Model
     * @param tableName 数据库表名
     * @param obj       对象
     * @return model
     */
    public Model assembleObjInfo(Model model, String tableName, TransportNewsDTO obj) {

        // 结果集返回一个map
        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();

        // 显示标题
        String showTitle = "详情";

        // 获取数据库中英文对照表主表信息
        TransportTableChineseEnglishDTO englishDTO = englishService.getByTableName(tableName);

        if (obj == null || englishDTO == null) {
            map.put("没有查询到数据！", "");
        } else {
            Map<String, Object> origin_map = GeneralUtils.ergodicModel(FastJsonUtils.toJSONString(obj), TransportNewsDTO.class);

            if (origin_map != null) {
                // 根据表ID（tableId）获取表字段信息
                TransportTableChineseEnglishDetailDTOQuery query = new TransportTableChineseEnglishDetailDTOQuery();
                query.setTableId(englishDTO.getId());
                query.setDeleteFlag(0);
                query.setPageSize(1000);
                Page<TransportTableChineseEnglishDetailDTO> detailPage = englishDetailService.getForPage(query);

                if (detailPage != null && detailPage.getItems().size() > 0) {
                    Object value;
                    String newfield;
                    for (TransportTableChineseEnglishDetailDTO item : detailPage.getItems()) {
                        if (item.getFrontShow() == 1) {
                            newfield = GeneralUtils.standardFields(item.getFieldName());
                            value = origin_map.get(newfield);
                            if (item.getFieldType().toUpperCase().equals("TIMESTAMP")) {
                                map.put(item.getFieldNameCn(), DateConvertUtils.cstToShortStrDate(value.toString()));
                            } else {

                                if (value == null || StringUtils.isBlank(value.toString())) {
                                    map.put(item.getFieldNameCn(), "--");
                                    continue;
                                }

                                //region 开始个性化设置
                                if (newfield.equals("adminId")) { //创建人
                                    value = manageService.getNickNameFromCache(Integer.valueOf(value.toString()));
                                }
                                if (newfield.equals("stopFlag")) { //启停用状态
                                    value = value.equals(0) ? "启用" : "停用";
                                }
                                //endregion

                                map.put(item.getFieldNameCn(), value.toString());
                            }
                        }
                    }
                }
            }
        }

        model.addAttribute("showTitle", showTitle);
        model.addAttribute("showResult", map);

        return model;
    }

    //endregion

    //以map的形式返回数据
    public List<Map<String, String>> getMapDataByQuery(TransportNewsDTOQuery objDTOQuery, String element) {
        return rpcService.getMapDataByQuery(objDTOQuery, element);
    }

}